package middleware

import (
	"dc-go/global"
	"dc-go/model"
	"dc-go/utils"
	"fmt"

	"github.com/gin-gonic/gin"
)

func RoleApiHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		err, roleList := GetUserRole(c)
		if err != nil {
			global.DcLogger.Error("获取用户角色失败! ")
			model.ResponseErrorMessage("获取用户角色失败! ", c)
			c.Abort()
			return
		}
		apiPath := c.Request.URL.RequestURI()
		apiMethod := c.Request.Method
		if len(roleList) == 0 {
			global.DcLogger.Error("没有分配角色, 你没有权限! ")
			model.ResponseErrorMessage("没有分配角色, 你没有权限! ", c)
			c.Abort()
			return
		}
		for _, v := range roleList {
			var roleApi model.SysRoleApi
			result := global.DcDb.Where("role_code = ? and api_path = ? and api_method = ?", v.RoleCode, apiPath, apiMethod).First(&roleApi)
			if result.RowsAffected != 0 {
				c.Next()
				return
			}
		}
		empee_acct := utils.GetEmpeeAcct(c)
		global.DcLogger.Error(fmt.Sprintf("【%s】 尝试【%s】 调用 【%s】 , 但没有权限! ", empee_acct, apiMethod, apiPath))
		model.ResponseErrorMessage("对不起, 你没有权限! ", c)
		c.Abort()
	}
}

func GetUserRole(c *gin.Context) (err error, role []model.SysRole) {
	empee_acct := utils.GetEmpeeAcct(c)
	var user model.SysUser
	err = global.DcDb.Preload("OrgRole").Where("empee_acct=?", empee_acct).First(&user).Error
	if err != nil {
		fmt.Println(err)
		return err, nil
	}
	// fmt.Printf("%+v\n", user)
	var orgRoles []model.SysOrgRole
	var roles []model.SysRole
	err = global.DcDb.Model(&user).Association("OrgRole").Find(&orgRoles)
	//fmt.Printf("orgRoles： %+v\n", orgRoles)
	if err != nil {
		fmt.Println(err)
		return err, nil
	}
	//err = global.DcDb.Model(&orgRoles).Association("Role").Find(&roles)
	roleCodes := make([]string, 0)
	for _, v := range orgRoles {
		roleCodes = append(roleCodes, v.RoleCode)
	}
	err = global.DcDb.Where("role_code in (?)", roleCodes).Find(&roles).Error
	//fmt.Printf("roles：%+v\n", roles)
	if err != nil {
		return err, nil
	}
	return nil, roles
}
